<?php

namespace Beerus\Modules\Push\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\cache\wiki\Union;
use Biz\model\push\PushLogModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

/**
 * Description: wwwroot
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/5/24
 * Time: 18:17
 */
class IndexController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $params['per_page'] = $page_size;
        $count = PushLogModel::count();
        $list = PushLogModel::select('*');

        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size
        ]);

        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('push_id', 'PUSH_ID')->placeholder('PUSH_ID');
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'id')->sortable();
                $grid->column('push_name', 'push名称');
                $grid->column('push_id', 'push_id');
                $grid->column('push_type', '推送类型')->using(
                    PushLogModel::PUSH_ARR
                    , '未知')->dot([
                    1 => 'warning',
                    2 => 'info',
                ]);
                $grid->column('creat_time', '创建时间')->sortable();
                $grid->column('end_time', '结束时间')->sortable();
                $grid->column('push_status', '状态')->using(
                    PushLogModel::STATUS_ARR
                    , '未知')->label([
                    1 => 'danger',
                    2 => 'success',

                ]);

                $grid->disableActions();
            }
        );
        return $content
            ->header('push')
            ->description(' ')
            ->breadcrumb(['text' => 'push列表', 'url' => '/push/index'])
            ->body($grid->render());
    }

    /**
     * 新增
     * @param Request $request
     * @param Content $content
     * @param Form $form
     * @return Content
     */
    public function create(Request $request, Content $content, Form $form): Content
    {
        $form->disableReset();
        $this->_getForm($form);
        $form->hidden('push_type')->default(PushLogModel::PUSH_TYPE_GENERAL);
        $form->confirm('确定新增吗？');
        $form->action('/admin/push/save');

        $tab = new Tab();
        $tab->add('固定文案创建', $form->render(), true);
        $tab->addLink('自定义文案推送创建', url('/admin/push/cusCreate'), false);
        $content->row($tab);
        return $content
            ->header('固定文案创建')
            ->description(' ')
            ->breadcrumb(
                ['text' => 'push列表', 'url' => '/push/index'],
                ['text' => '新增']
            );

    }

    public function cusCreate(Request $request, Content $content, Form $form)
    {
        $form->disableReset();
        $form->confirm('确定新增吗？');
        $form->action('/admin/push/save');
        $form->text('push_id', 'PUSH_ID')->required()->help('请联系相关推送业务负责人获取push_id');
        $form->text('name', 'push名称')->required();
        $form->text('url', '链接')->required();
        $form->hidden('push_type')->default(PushLogModel::PUSH_TYPE_SPECIAL);

//        $form->datetime('start_time', '开始时间')->required();
        $form->list('title', '标题')->help('如果想将对应Excel列加入title，可将该列单独作为一行编写。例如:A(大写字母哦)');
        $form->list('alert', '副标题')->help('ssss');

        $form->file('file', '文件')->required()->removable();
        $tab = new Tab();
        $tab->addLink('固定文案创建', url('/admin/push/index/create'), false);
        $tab->add('自定义文案推送创建', $form->render(), true);
        $content->row($tab);
        return $content
            ->header('自定义文案推送创建')
            ->description(' ')
            ->breadcrumb(
                ['text' => 'push列表', 'url' => '/push/index'],
                ['text' => '新增']
            );

    }

    /**
     * form
     * @param $baseForm
     */
    private function _getForm($baseForm)
    {
        $baseForm->text('push_id', 'PUSH_ID')->required()->help('请联系相关推送业务负责人获取push_id');
        $baseForm->text('name', 'push名称')->required();
        $baseForm->text('title', '标题')->required();
        $baseForm->text('alert', '副标题')->required();
        $baseForm->text('url', '链接')->required();
//        $baseForm->datetime('start_time', '开始时间')->required();

        $baseForm->file('file', '文件')->required()->removable();
    }

    /**
     * 保存
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function save(Request $request)
    {
        $params = $request->all();
        $type = $params['push_type'];
        try {
            $file = $params['file'];
            $fileName = '/tmp/push-' . $params['push_id'] . '-' . date('YmdHis') . '.xls';
            $res = move_uploaded_file($file, $fileName);
            if (!$res) {
                throw new \Exception('保存文件失败');
            }
            $data['push_id'] = $params['push_id'];
            $data['push_name'] = $params['name'];
            if ((int)$type === PushLogModel::PUSH_TYPE_GENERAL) {
                $data['alert'] = $params['alert'];
                $data['title'] = $params['title'];
            } else {
                $data['alert'] = json_encode($params['alert'], JSON_THROW_ON_ERROR);
                $data['title'] = json_encode($params['title'], JSON_THROW_ON_ERROR);
            }
            $data['url'] = $params['url'];
            $data['push_type'] = $type;
            $data['file_name'] = $fileName;
            $data['create_admin_id'] = Admin::user()->id;
            $where['push_id'] = $params['push_id'];
            $isset = PushLogModel::value($where);

            if (!is_null($isset)) {
                PushLogModel::update($data, $where);
            } else {
                PushLogModel::insert($data);
                $id = PushLogModel::id();
                if (!$id) {
                    throw new \Exception('sql保存信息失败');
                }
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '请重试,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '上传成功'
        ]);
        return redirect('/admin/push/index')->with(compact('success'));
    }
}